package com.i2863.shiroDemo.web;

import com.i2863.shiroDemo.dto.MenuInfo;
import com.i2863.shiroDemo.dto.ResultInfo;
import com.i2863.shiroDemo.dto.RoleInfo;
import com.i2863.shiroDemo.dto.UserInfo;
import com.i2863.shiroDemo.util.StringUtils;
import com.i2863.shiroDemo.service.IPermissionService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("menu")
public class MenuController extends BaseController {

    @Resource
    private IPermissionService iPermissionService;

    @RequestMapping("left")
    @ResponseBody
    public ResultInfo<List<MenuInfo>> getMenuInfoList(@RequestParam("code") String code) {
        List<MenuInfo> menuInfoList = new ArrayList<>();
        //获取当前用户角色信息
        UserInfo userInfo = this.getUserInfo();
        if (userInfo == null) {
            return new ResultInfo<>(menuInfoList);
        }
        RoleInfo roleInfo = userInfo.getRoleInfo();
        if (roleInfo == null || StringUtils.isEmpty(roleInfo.getPermissionIds())) {
            return new ResultInfo<>(menuInfoList);
        }
        //获取权限菜单信息
        List<MenuInfo> allMenuInfoList = iPermissionService.getMenuPermissions(code);
        if (allMenuInfoList == null || allMenuInfoList.isEmpty()) {
            return new ResultInfo<>(menuInfoList);
        }
        //获得有权限访问菜单
        if (SecurityUtils.getSubject().isPermitted("*")) {
            menuInfoList.addAll(allMenuInfoList);
        } else {
            allMenuInfoList.stream().filter(menuInfo -> roleInfo.getPermissionIds().contains("," + menuInfo.getOnlyId() + ",")).forEach(info -> {
                if (info.getChildren() != null) {
                    List<MenuInfo> subMenuInfoList = new ArrayList<>();
                    info.getChildren().stream().filter(subInfo -> roleInfo.getPermissionIds().contains("," + subInfo.getOnlyId() + ",")).forEach(subMenuInfoList::add);
                    info.setChildren(subMenuInfoList);
                }
                menuInfoList.add(info);
            });
        }
        return new ResultInfo<>(menuInfoList);
    }

}
